

google.load("jquery", "1.5.0");


function OnLoad() {
	$("#submitUpload").click(function(e) {
		e.preventDefault();
		
		var stationLines = $("#inputStations").val().split("\n");
		var i;
		var stations = [];
		for (i = 0; i < stationLines.length; ++i) {
			var columns = stationLines[i].split(",");
			if (columns.length < 2)
				continue;
			var trainCode = parseInt(columns[0]);
			if (isNaN(trainCode))
				continue;
			var name = columns[1];
			if (name.length == 0)
				continue;
			stations.push({trainCode : trainCode, name : name});
		}
		
		var creation = function() {
			if (stations.length == 0)
				return;
			var item = stations.pop();
			
			$.ajax({
					url			: "/rest/trains/" + item.trainCode, 
					data		: JSON.stringify(item),
					type		: "PUT",
					contentType	: "application/json; charset=utf-8",
					processdata	: false,
					success		: function(data) { alert("success"); },
					error		: function(e) { alert("error"); }
					});
			creation();
		};
		creation();		
	});
}
google.setOnLoadCallback(OnLoad);
